//
//  CAForumDetailController.m
//  cascade-realm
//
//  Created by QSC on 3/6/24.
//

#import "CAForumDetailController.h"
#import "CAForumHeaderCell.h"
#import "CAForumCommentCell.h"
#import "RecordAlertView.h"

@interface CAForumDetailController ()<UITableViewDataSource>
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)UIView* bottomView;
@property (nonatomic,strong)UIButton * talkBtn;
@property (nonatomic,strong)UITextField * textFiled;
@property (nonatomic,strong)UIView* textView;
@property (nonatomic,strong)RecordAlertView * alertView;

@end

@implementation CAForumDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setUpNavView];
    
    [self setBottomView];
    
    [self.view insertSubview:self.tableView atIndex:0];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
  
    
}

- (void)setUpNavView{
    
    [self.navView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(90);
    }];
    
    [self.backBtn setImage:Img(@"back2") forState:UIControlStateNormal];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navView).offset(KNavigationStatusHeight * 0.5);
        make.left.equalTo(self.navView).offset(20);
        make.size.mas_equalTo(28);
    }];
    

    UIButton * moreBtn = [UIButton buttonWithType: UIButtonTypeCustom];
    [moreBtn setImage:Img(@"detail_more") forState:UIControlStateNormal];
    [self.navView addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.backBtn);
        make.right.equalTo(self.navView).offset(-20);
        make.size.mas_equalTo(28);
    }];
    [moreBtn addTarget:self action:@selector(moreClick) forControlEvents:UIControlEventTouchUpInside];
  
    moreBtn.hidden = [self.model.binduserId isEqualToString:CAUserInfo.shared.userInfo.userId];
   

}

- (void)moreClick{
    
    [Tool moreClick:self.model.binduserId];
}

- (void)setBottomView{
    UIView * bottomView = [UIView new];
    self.bottomView = bottomView;
    bottomView.backgroundColor = [UIColor whiteColor];
    
    UIView * line = [UIView new];
    line.backgroundColor = Hex(0xEDEDED);
    [bottomView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(bottomView);
        make.height.mas_equalTo(1);
    }];
    
    UIButton * callBtn = [UIButton buttonWithType: UIButtonTypeCustom];
    [callBtn setImage:Img(@"call_normal") forState:UIControlStateNormal];
    [callBtn setImage:Img(@"call_selected") forState:UIControlStateSelected];
    [callBtn addTarget:self action:@selector(callDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:callBtn];
    [callBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView).offset(20);
        make.top.equalTo(bottomView).offset(17);
        make.size.mas_equalTo(34);
    }];
    
    
    UIButton * talkBtn = [UIButton ButtonWithFont:Font(14) color:[UIColor whiteColor] text:@"Hold to talk"];
    self.talkBtn = talkBtn;
    talkBtn.backgroundColor = Hex(0xCEE701);
    [bottomView addSubview:talkBtn];
    talkBtn.layer.cornerRadius = 17;
    talkBtn.clipsToBounds = YES;
    
    UIView *textView = [UIView new];
    textView.backgroundColor = Hex(0xF6F8FA);
    textView.layer.cornerRadius = 17;
    [bottomView addSubview:textView];
    UITextField * textField = [UITextField new];
 
    textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Enter your ideas..." attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
    textField.font = Font(10);

    [textView addSubview:textField];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(textView);
        make.left.right.equalTo(textView).inset(12);
    }];
    self.textFiled = textField;
    self.textView = textView;
    
    UIButton * sendBtn = [UIButton buttonWithType: UIButtonTypeCustom];
    [sendBtn setImage:Img(@"send") forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:sendBtn];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView).offset(-20);
        make.size.equalTo(callBtn);
        make.centerY.equalTo(callBtn);
    }];
    
    [talkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(callBtn);
        make.left.equalTo(callBtn.mas_right).offset(20);
        make.height.equalTo(callBtn);
        make.right.equalTo(sendBtn.mas_left).offset(-20);
    }];
    
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(talkBtn);
    }];
    
    UILongPressGestureRecognizer * lp = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [talkBtn addGestureRecognizer:lp];
    
    
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(kBottomSafeHeight + 60);
    }];
}

- (void)sendClick{
    
    if (!self.textFiled.hasText) {
        return;
    }
    
    CAComment * comment = [CAComment new];
    comment.content = self.textFiled.text;
    comment.name = CAUserInfo.shared.userInfo.nickname;
    comment.avatar = CAUserInfo.shared.userInfo.avatarThumbUrl;
    comment.type = 1;
    
    
    if (self.model.commentArray == nil) {
        self.model.commentArray = [NSMutableArray array];
    }
    
    [Tool ShowLoading];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [Tool HideLoading];
        self.textFiled.text = @"";
        [self.model.commentArray addObject:comment];
        
        [self.model save];
        
        [self.tableView reloadData];
    });
    
}

- (void)sendRecord{
  

    
    CAComment * comment = [CAComment new];
   
    comment.name = CAUserInfo.shared.userInfo.nickname;
    comment.avatar = CAUserInfo.shared.userInfo.avatarThumbUrl;
    comment.type = 2;
    comment.path = RecordTool.shared.path;
    comment.recordTime = RecordTool.shared.recordTime;
    
    if (comment.recordTime < 1) {
        [EasyTextView showText:@"The voice length must be greater than 1 second"];
        return;;
    }
    
    
    if (self.model.commentArray == nil) {
        self.model.commentArray = [NSMutableArray array];
    }
    
    [Tool ShowLoading];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [Tool HideLoading];
     
        [self.model.commentArray addObject:comment];
        
        [self.model save];
        
        [self.tableView reloadData];
    });
}


- (void)callDidClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    self.talkBtn.hidden = !btn.selected;
    self.textView.hidden = btn.selected;

}


- (void)longPress:(UILongPressGestureRecognizer *)lp{
    CGPoint p = [lp locationInView:self.view];
    
    switch (lp.state) {
        case UIGestureRecognizerStateBegan:
            
            [RecordTool startRecord];
            self.alertView = [RecordAlertView show];
 
            break;
        case UIGestureRecognizerStateEnded:
           
            
            [RecordTool stopRecord];
            
            if (self.alertView.isSend) {
                [self sendRecord];
            }

            [self.alertView removeFromSuperview];
            
            break;
        case UIGestureRecognizerStateChanged:
            
            [self.alertView changeMode:p.y];
            break;
        default:
            break;
    }
    
}


- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        [_tableView registerClass:[CAForumHeaderCell class] forCellReuseIdentifier:@"CAForumHeaderCell"];
        [_tableView registerClass:[CAForumCommentCell class] forCellReuseIdentifier:@"CAForumCommentCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
  
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    return  _tableView;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.model.commentArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        CAForumHeaderCell* cell = [tableView dequeueReusableCellWithIdentifier:@"CAForumHeaderCell"];
        cell.model = self.model;
        
        return  cell;
    }
    
    CAForumCommentCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CAForumCommentCell"];
    
    cell.comment = self.model.commentArray[indexPath.row -1];
    
    WeakSelf
    cell.saveBlock = ^{
        [weakSelf.model save];
    };
    
    return  cell;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
@end
